import axios from 'axios'
import store from '../store'
import router from '../router'
import { getToken } from '@/utils/auth'
import { Message, MessageBox } from 'element-ui'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_API_URL,
  headers: {
    // 'AUTH-SYS': 'admin'
  },
  timeout: 50000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers.token = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  (response) => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.code !== 20000) {
      Message({
        message: res.msg || '网络错误',
        type: 'error'
      })

      // 50015  access_token不合法
      // 50021: access_token过期,
      // 50022: access_token失效,
      if (res.code === 61000 || res.code === 50021 || res.code === 50022) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => store.dispatch('FedLogOut'))
          .then(() => {
            // redirectToOA()
            router.beforeEach((to, from, next) => {
              // to and from are both route objects. must call `next`.
              next({ path: '/login' })
            })
          })
      }
      return Promise.reject(res)
    } else {
      return res
    }
  },
  (error) => {
    Message({
      message: error.message,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

export default service
